<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>计算属性</title>
    </head>
    <body>
        <div id="app">
            <h1>{{fullName}}</h1>
            <h2>总价格: {{totalPrice}}</h2>
        </div>
    </body>
    <script src="../js/vue.js" charset="utf-8"></script>
    <script type="text/javascript">
        const app = new Vue({
            el: '#app',
            data: {
                books: [
                    {id: 100, name: '代码大全', price: 100},
                    {id: 101, name: '龙族', price: 50},
                    {id: 102, name: '人性的弱点', price: 20},
                    {id: 103, name: '编译原理', price: 89}
                ],
                firstName: 'Kobe',
                lastName: 'Bryant'
            },
            computed: { // 计算属性存在缓存, 值不改变时直接使用缓存
                totalPrice: function() {
                    let result = 0;
                    for (let book of this.books) {
                        result += book.price;
                    }
                    return result;
                },
                fullName: {
                    // 计算属性一般只实现 get 方法, 只读属性
                    set: function (newValue) {
                        // console.log('set 方法调用');
                        const values = newValue.split(' ');
                        this.firstName = values[0];
                        this.lastName = values[1];
                    },
                    get: function () {
                        console.log("get 方法调用")
                        return this.firstName + ' ' + this.lastName;
                    }
                }
            }
        });
    </script>
</html>
